<extend name="../app/Admin/View/default/common/dashboard_layout.html"/>
<block name="content">
<style>
    .register_name{
        position: absolute;
        top: 30px;
        left: 20px;
        color: #999;
    }    
    .subbody{
        position: absolute;
        color: #999;
    }
    #sms_body{
        height: 200px;
        resize: none;
    }
</style>

<section class="content-header clearfix">
    <h1 class="pull-left">群发短信
        <i class="fa fa-question-circle page-tooltip" data-toggle="tooltip" data-original-title="" data-placement="bottom"></i>
    </h1>
</section>

<section class="content" n-id="{$send_id}">
    <div class='row'>
        <div class='col-xs-12'>
            <div class="box box-solid">
                <div class="box-body">
                    <div class="row">
                        <div class='col-md-12'>
                            <div class='form-group'>
                                <p>账户余额: ￥<span style='color:red'>{$balance}</span></p>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="">收件人</label>
                                <select name="receiver[]" class="js-data-example-ajax form-control"  multiple="multiple">
                                </select>
                            </div>
                        </div>
                        
                        <present name="receiver">
                            <div class="col-md-12">
                                <div id="from_container" class="form-group">
                                    <p><b>从其他模块传递过来的收件人：</b></p>
                                    <volist name="receiver" id="rec">
                                        <label class="radio-inline">
                                            <input type="checkbox" name="from_phones" checked="true" value="{$rec.telephone}">{$rec.name}
                                        </label>
                                    </volist>
                                </div>
                            </div>
                        </present>
                        
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="">短信内容</label>
                                <span class="register_name">{$sms_body_prefix}</span>
                                <textarea class="form-control" id="sms_body" name="body">{$h_log.body}</textarea>
                                <span class="subbody">{$sms_body_suffix}</span>
                            </div>
                        </div>
                        <div class="col-md-7">
                            <p>共<span style="color:red" id="sms_count"></span>个字符,拆分成<span style="color:red" id="sms_split"></span>条短信</p>
                        </div>
                        <div class="col-md-5">
                            <div class="form-group">
                                <span>内容中联系人的</span>
                                <select id="var_select">
                                    <volist name="var_list" id="var">
                                        <option>{$key}</option>
                                    </volist>
                                </select>
                                <span>可以用<i class="hi hi-hand-top"></i></span><span class="replacer_label"><a href="javascript:void(0)" id="column_replacer" onclick="add_user_name_label();">[#{:key($var_list)}#]</a></span><span>进行替换</span>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <div class="row">
                                <div class="col-xs-2">
                                    <button id="send" class="btn btn-primary btn-block" type="button"><i class="fa fa-envelope"></i> 发送短信</button>
                                </div>
                                <div class="col-xs-10">
                                    <div class="send_sms_progressbar" style="display:none;">
                                        <div id="progressbar" ></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    
<link href="__PUBLIC__/libs/select2/select2.min.css" rel="stylesheet" type="text/css" />
<link href="__PUBLIC__/libs/jquery-ui-1.11.4/jquery-ui.theme.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="__PUBLIC__/libs/select2/select2.full.js"></script>
<script type="text/javascript" src="__PUBLIC__/libs/select2/zh-CN.js"></script>
<script type="text/javascript" charset="utf-8" src="__PUBLIC__/libs/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
    
    function formatRepo(repo) {
        if (repo.loading)
            return repo.text;
        var markup = '<span>' + repo.text + '</span>';
        return markup;
    }

    function formatRepoSelection(repo) {
        return repo.text;
    }
    
    function freshContainer(e){
        var $container = $('#container');
        var div = 'tag_phones_';
        
        var tag_id = e.params.data.id;
        var tag_name = e.params.data.text;
        var selected = e.params.data.selected;
        
        if(selected == true){
            $.ajax({
                cache:true,
                type: "GET",
                url: "{:U('/admin/Sms/getPhoneByTag')}",
                data:"tag_id="+tag_id,
                error:function(request){
                    alert('获取信息失败！');
                },
                success: function(data){
                    var $div = $('<div id="'+div+tag_id + '"></div>');
                    $div.html('<div style="margin-top:15px"><b>'+tag_name+'</b></div>');
                    for(var i=0;i<data.length;i++){
                        $div.append('<label class="radio-inline"><input type="checkbox" name="phones" checked="true" value="' + data[i].phone + '"/> ' + data[i].name+'</label>');
                    }
                    $container.append($div);
                }
            });
        }
        else{
            $('#'+div+tag_id).remove();
        }
    }
    
    function getCheckBoxCheckedValue(name){
        var values = [];
        $('input:checkbox[name='+name+']:checked').each(function(){
            values.push($(this).val());
        });
        return values;
    }
    
    function add_user_name_label() {
        var column_replacer = $("#column_replacer").html();
        $("#sms_body").val($("#sms_body").val() + column_replacer);
      }
    
    function setCursorPosition(ctrl, pos){ 
        if(ctrl.setSelectionRange){ 
            ctrl.focus(); 
            ctrl.setSelectionRange(pos,pos); 
        } 
        else if (ctrl.createTextRange) { 
            var range = ctrl.createTextRange(); 
            range.collapse(true); 
            range.moveEnd('character', pos); 
            range.moveStart('character', pos); 
            range.select(); 
        } 
    }
    
    function sms_count() {
        var sms_prefix_count = $('.register_name').text().length;
        var sms_suffix_count = $('.subbody').text().length;
        
        var body_count = $('#sms_body').val().length;
        
        var sms_count = sms_prefix_count+body_count+sms_suffix_count;
        var sms_split = 0;
        if(sms_count <= 70){
            sms_split = Math.ceil(sms_count/70);
        }
        else{
            sms_split = Math.ceil(sms_count/67);
        }
        $('#sms_count').text(sms_count);
        $('#sms_split').text(sms_split);
    }
    
        
    $(function(){
        
        sms_count();
        
        //调整短信固定尾部内容的位置
        var sms_body_width = parseInt($('#sms_body').css('width'));
        var sms_body_height = parseInt($('#sms_body').css('height'));
        var suffix_length = parseInt($('.subbody').css('width'));
        var prefix_length = $('.register_name').css('width');
        
        //光标缩进，光标焦点在备案字后
        $('.subbody').css('top', sms_body_height + 'px').css('left', (sms_body_width - suffix_length) + 'px');
        $('#sms_body').css('text-indent', prefix_length);
        
        //计算短信字数
        $('#sms_body').keyup(function(){
            sms_count();
        });
        
        $("#progressbar").progressbar({
          value: 0
        });
        
        
        progressbar = $( "#progressbar" ),
        progressbarValue = progressbar.find( ".ui-progressbar-value" );
        
        progressbarValue.css({
            "width":"90%",
            "background": '#00CACA',
            "height":"15px"
        });
        
        
        $('#var_select').on('change', function(){
            $('#column_replacer').html("[#" + $(this).val() + "#]");
        });
        
        $('#send').on('click', function(){
            
            
            var sms_prefix = $('.register_name').text();
            var sms_suffix = $('.subbody').text();
            
            if($("#sms_body").val() == ''){
                alert('请填写短信内容');
                return;
            }
            
            var body = sms_prefix + $("#sms_body").val() + sms_suffix;
            var receiver = $('.js-data-example-ajax').select2("val");
            var phones = getCheckBoxCheckedValue('phones');
            var from_phones = getCheckBoxCheckedValue('from_phones');
            
            if(receiver == null){
                receiver = [];
            }
            
            var to = $.unique($.merge($.merge(receiver, phones), from_phones));
            var queue_num = 100;
            
            
            if(to.length <= 0){
                alert('请填写要发送的手机');
                return;
            }
            
            
            
            $(this).attr('disabled', true);
            $(this).text('发送中..');
            
            
            
             progressbar.progressbar("option", {
                value: 0.001
              });
            $('.send_sms_progressbar').show();
            
            
            
            var n = 0;
            var success_queue = 0;
            var total = Math.ceil(to.length / queue_num);
            while(n<to.length){
                var start = n;
                var end = n + queue_num;
                $.ajax({
                    type: "POST",
                    url: "{:addons_url('SmsBatchSend://SmsBatch/send_sms')}",
                    data:{
                        to:to.slice(start,end).join(","),
                        body:body
                    },
                    error:function(request){
                        alert('获取信息失败！');
                    },
                    success: function(data){
                        console.log(data);
                        if(data.status ==0){
                            alert(data.err_msg);
                        };
                        success_queue++;
                        progressbar.progressbar( "option", {
                            value: Math.floor( (success_queue / total) * 100 )
                          });

                        if(success_queue == total){
                            $('#send').attr('disabled', false);
                            $('#send').text('发送');

                            $('.send_sms_progressbar').fadeOut();
                            window.location = "{:addons_url('SmsBatchSend://SmsBatch/smsLog')}";
                        }
                    }
                });
                n = n + queue_num;
                
            }
            
        });
        
//        $select2_tag = $('.select2-tag');
//        
//        $select2_tag.on("select2:select", function (e) { freshContainer(e) });
//        
//        $select2_tag.on("select2:unselect", function(e){ freshContainer(e) });
        
        $('.js-data-example-ajax').select2({
            language: "zh-CN",
            tags:true,
            ajax: {
                url: "<?php echo U('Api/User/searchByPhone', array('key' => 'telephone')); ?>",
                dataType: 'json',
                delay: 250,

                //请求参数（GET）
                data: function(params) {
                    return {
                        phone: params.term,
                        page: params.page
                    };
                },

                processResults: function(data, page) {
                    $(".js-data-example-ajax option:selected").each(function() {
                        var $this = $(this);
                        if ($this.length) {
                            var selText = $this.text();
                        }
                    });

                    //返回构造结果
                    return {
                        results: data.items
                    };
                },
                cache: true
            },

            //字符转义处理
            escapeMarkup: function(markup) {
                return markup;
            },
            minimumInputLength: 1,
            templateResult: formatRepo,
        });
        
        //$('.select2-tag').select2();
        
       
    });
    
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };

    //给数组增加删除方法
    Array.prototype.remove = function(val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
    </script>
</section>
</block>